package com.kuzlak.cms.module.sys.controller;


import com.kuzlak.cms.bean.Result;
import com.kuzlak.cms.config.ConstantHeader;
import com.kuzlak.cms.constant.ResultConstant;
import com.kuzlak.cms.module.sys.entity.SysAddress;
import com.kuzlak.cms.module.sys.entity.SysLoginLog;
import com.kuzlak.cms.module.sys.service.SysAddressService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Hesenjan(Serkol)
 * @since 2021-12-27
 */
@Tag(name = "地区管理")
@RestController
@RequestMapping("/api/address")
public class AddressController {

    @Autowired
    private SysAddressService service;

    @Operation(summary= "地址查询")
    @PostMapping("/list")
    public Result list(
            @RequestParam(name = "id", defaultValue = "0") long id

    ) {

        Result gridResult = new Result();
        List<SysAddress> page1 = service.finbyIdList(id);


        gridResult.setData(page1);
        gridResult.setCode(ResultConstant.SUCSESS);

        return gridResult;

    }

    @Operation(summary= "地址树形查询")
    @PostMapping("/listTree")
    public Result listTree(
            @RequestParam(name = "key", defaultValue = "0") long key,
            @RequestParam(name = "level", defaultValue = "1") int level
    ) {

        Result gridResult = new Result();
        List<Map<String, Object>> page1 = service.findByTreeList(key,level);


        gridResult.setData(page1);
        gridResult.setCode(ResultConstant.SUCSESS);

        return gridResult;

    }

    @Operation(summary= "添加或编辑")
    @PostMapping("edit")
    public Result edit(@Valid SysAddress data) {
        SysLoginLog adminToken = ConstantHeader.getAdminToken();

        boolean flag = false;
        if (data.getId() != null && data.getId() > 0) {
            flag = service.updateById(data);
        } else {

            flag = service.save(data);
        }

        return flag ? Result.ok() : Result.failure();
    }


    @Operation(summary= "删除")
    @PostMapping("delete")
    public Result status(
            @RequestParam(name = "id", defaultValue = "0") long id
    ) {
        Result result = new Result();
        if (id > 0) {
            boolean update = service.deleteById(id);
            if (update) {

                result.setCode(ResultConstant.SUCSESS);
            } else {
                result.setCode(ResultConstant.FAIL);
            }
        } else {
            result.setCode(ResultConstant.EMPTIY);
        }

        return result;
    }

}

